package com.yeook.ymax.db;

import java.io.IOException;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.yeook.ymax.ui.activitys.UILApplication;
import com.yeook.ymax.ui.entity.RingtoneView;
import com.yeook.ymax.ui.entity.WallaperView;

public class Database {
	public static SQLiteDatabase database = null;
	private DbStructure dbhandler;
	static Context context = UILApplication.getContext();
	private int i = 0;

	private Database() {
		dbhandler = new DbStructure(context);
		//database = dbhandler.getWritableDatabase();
		database = dbhandler.openDataBase();
	}

	private static class SingletonHolder {
		public static final Database INSTANCE = new Database();
	}

	public static Database getInstance() {
		return SingletonHolder.INSTANCE;
	}

	public void insertHash(String hash, String type) {
		ContentValues values = new ContentValues();
		values.put(DbStructure.COLUMN_HASH, hash);
		values.put(DbStructure.COLUMN_TYPE, type);
		database.insert(DbStructure.TABLE_HASHES, null, values);

	}

	public String getTopHash(String type) {
		String return_string = "0";
		Cursor c = null;
		yield();
		try {
			c = database.query(DbStructure.TABLE_HASHES,
					new String[] { DbStructure.COLUMN_HASH }, "type = ?",
					new String[] { type }, null, null, "hash desc");

			if (c.moveToFirst()) {
				if (c.getString(0).length() > 0) {
					return_string = c.getString(0);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			c.close();
		}
		return return_string;
	}

	private void yield() {
		try {
			if (database.yieldIfContendedSafely(1000)) {
				System.out.println("Yelded at id: " + i);
			}
		} catch (Exception e) {
		}
		;
	}
	
	public Cursor getWallpaperViews(Integer cateCode)
	{
		Cursor c = null;
		yield();
		try {
			c = database
					.rawQuery(
							"select distinct a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.attachmentId  " +
							" from table_wallpaper as a where a.cateCode = ? order by random() LIMIT 500 ",
							new String[] { cateCode + "" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public Cursor getRingtoneViews(Integer cateCode)
	{
		Cursor c = null;
		yield();
		try {
			c = database
					.rawQuery(
							"select distinct a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.tags  " +
							" from table_ringtone as a where a.cateCode = ? order by random() LIMIT 500 ",
							new String[] { cateCode + "" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	/**
	 * 收藏壁纸
	 * @param uniqueId
	 */
	public void favoriteWallpaper(Integer uniqueId)
	{
		  ContentValues values = new ContentValues();
	      values.put(DbStructure.COLUMN_FAVORITE, 1);
	      database.update(DbStructure.TABLE_WALLPAPER, values, "uniqueId = ?", new String[]{uniqueId + ""});
	}
	
	public void favoriteRingtone(Integer uniqueId)
	{
		  ContentValues values = new ContentValues();
	      values.put(DbStructure.COLUMN_FAVORITE, 1);
	      database.update(DbStructure.TABLE_RINGTONE, values, "uniqueId = ?", new String[]{uniqueId + ""});
	}
	
	/**
	 * 取消收藏
	 * @param uniqueId
	 */
	public void cancleFavoriteWallpaper(Integer uniqueId)
	{
		ContentValues values = new ContentValues();
	      values.put(DbStructure.COLUMN_FAVORITE, 0);
	      database.update(DbStructure.TABLE_WALLPAPER, values, "uniqueId = ?", new String[]{uniqueId + ""});
	}
	
	public void cancleFavoriteRingtone(Integer uniqueId)
	{
		ContentValues values = new ContentValues();
	      values.put(DbStructure.COLUMN_FAVORITE, 0);
	      database.update(DbStructure.TABLE_RINGTONE, values, "uniqueId = ?", new String[]{uniqueId + ""});
	}
	
	
	/**
	 * 获取收藏的壁纸
	 * @return
	 */
	public Cursor getWallpaperFavorite()
	{
		Cursor c = null;
		yield();
		try {
			c = database
					.rawQuery(
							"select a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.attachmentId " +
							" from table_wallpaper as a where a.favorite = ? ",
							new String[] { "1" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public Cursor getRingtoneFavorite()
	{
		Cursor c = null;
		yield();
		try {
			c = database
					.rawQuery(
							"select a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.tags " +
							" from table_ringtone as a where a.favorite = ? ",
							new String[] { "1" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public void clearWallpaperViresHistory()
	{
		database.delete(DbStructure.TABLE_HISTORY, "type = ?",
				new String[] { "wallpaper" });
	}
	
	public void clearRingtoneViresHistory()
	{
		database.delete(DbStructure.TABLE_HISTORY, "type = ?",
				new String[] { "ringtone" });
	}
	
	public WallaperView getWallaperView(Integer uniqueId)
	{
		Cursor cursor = null;
		WallaperView wallaperView = new WallaperView();
		yield();
		try {
			cursor = database
					.rawQuery(
							"select a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.attachmentId " +
							" from table_wallpaper as a where a.uniqueId = ? ",
							new String[] { uniqueId + "" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			wallaperView.setCateCode(cursor.getInt(6));
			wallaperView.setDescription(cursor.getString(2));
			wallaperView.setFileName(cursor.getString(5));
			wallaperView.setLable(cursor.getString(4));
			wallaperView.setUniqueId(cursor.getLong(3));
			wallaperView.setDate(new Date(cursor.getLong(7)));
			wallaperView.setAttachmentId(cursor.getLong(8));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
			cursor.close();
		}
		
		return wallaperView;
	}
	
	public RingtoneView getRingtoneView(Integer uniqueId)
	{
		Cursor cursor = null;
		RingtoneView ringtoneView = new RingtoneView();
		yield();
		try {
			cursor = database
					.rawQuery(
							"select a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.tags " +
							" from table_ringtone as a where a.uniqueId = ? ",
							new String[] { uniqueId + "" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			ringtoneView.setCateCode(cursor.getInt(6));
			ringtoneView.setDescription(cursor.getString(2));
			ringtoneView.setFileName(cursor.getString(5));
			ringtoneView.setLable(cursor.getString(4));
			ringtoneView.setUniqueId(cursor.getLong(3));
			ringtoneView.setDate(new Date(cursor.getLong(7)));
			ringtoneView.setTags(cursor.getString(8));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
			cursor.close();
		}
		
		return ringtoneView;
	}
	
	/**
	 * 获取壁纸的历史浏览记录
	 * @return
	 */
	public Cursor getWallpaperViewsHistory()
	{
		Cursor c = null;
		yield();
		try {
			c = database
					.rawQuery(
							"select a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.attachmentId  " +
							" from table_wallpaper as a, table_history as h where a.uniqueId = h.uniqueId and h.type = ? ", new String[] { "wallpaper" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public Cursor getRingtoneViewsHistory()
	{
		Cursor c = null;
		yield();
		try {
			c = database
					.rawQuery(
							"select a._id, a.dwn, a.description, a.uniqueId, a.lable, a.fileName, a.cateCode, a.date, a.tags  " +
							" from table_ringtone as a, table_history as h where a.uniqueId = h.uniqueId and h.type = ? ", new String[] { "ringtone" });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public void deleteHistory(Integer uniquer_id)
	{
		database.delete(DbStructure.TABLE_HISTORY, "uniqueId = ?",
				new String[] { uniquer_id + "" });
	}
	
	@SuppressLint("SimpleDateFormat")
	public void insertHistory(Integer uniquer_id, String type)
	{
		try{
			deleteHistory(uniquer_id);
		}catch(Exception ex){ex.printStackTrace();}
		
		ContentValues values = new ContentValues();
		values.put(DbStructure.COLUMN_UNIQUER_ID, uniquer_id);
		values.put(DbStructure.COLUMN_TYPE, type);
		Date date=new Date();
		values.put(DbStructure.COLUMN_DATE, date.getTime());
		database.insert(DbStructure.TABLE_HASHES, null, values);
	}

	public void insertWallaperView(WallaperView wallaperView) {

		try {

			ContentValues values = new ContentValues();
			values.put(DbStructure.COLUMN_DWN, wallaperView.getDwn());
			values.put(DbStructure.COLUMN_FAVORITE, 0);
			values.put(DbStructure.COLUMN_DATE, wallaperView.getDate().getTime());
			values.put(DbStructure.COLUMN_DESCRIPTION,
					wallaperView.getDescription());
			values.put(DbStructure.COLUMN_UNIQUER_ID,
					wallaperView.getUniqueId());
			values.put(DbStructure.COLUMN_ATTACHMENTID,
					wallaperView.getAttachmentId());
			values.put(DbStructure.COLUMN_LABLE, wallaperView.getLable());
			values.put(DbStructure.COLUMN_FILE_NAME, wallaperView.getFileName());
			values.put(DbStructure.COLUMN_CATE_CODE, wallaperView.getCateCode());
			database.insert(DbStructure.TABLE_WALLPAPER, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
		yield();
	}
	
	public void insertRingtoneView(RingtoneView ringtoneView) {

		try {

			ContentValues values = new ContentValues();
			values.put(DbStructure.COLUMN_DWN, ringtoneView.getDwn());
			values.put(DbStructure.COLUMN_FAVORITE, 0);
			values.put(DbStructure.COLUMN_DATE, ringtoneView.getDate().getTime());
			values.put(DbStructure.COLUMN_DESCRIPTION,
					ringtoneView.getDescription());
			values.put(DbStructure.COLUMN_UNIQUER_ID,
					ringtoneView.getUniqueId());
			values.put(DbStructure.COLUMN_TAGS,
					ringtoneView.getTags());
			values.put(DbStructure.COLUMN_LABLE, ringtoneView.getLable());
			values.put(DbStructure.COLUMN_FILE_NAME, ringtoneView.getFileName());
			values.put(DbStructure.COLUMN_CATE_CODE, ringtoneView.getCateCode());
			database.insert(DbStructure.TABLE_RINGTONE, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
		yield();
	}
}
